package com.itheima.controller;


import com.github.pagehelper.Page;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CategoryMenu;
import com.itheima.service.CategoryMenuService;
import com.itheima.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/categoryMenu")
public class CategoryMenuController {

    @Autowired
    private CategoryMenuService categoryMenuService;

    //获取菜单列表
    @PostMapping("/getList")
    public Result getList(@RequestBody Map<String,Object> categoryMenuVO){
        Page<CategoryMenu> categoryMenuPage = categoryMenuService.findAll(categoryMenuVO);
        PageResult<CategoryMenu> pageResult=new PageResult<>();
        pageResult.setTotal(categoryMenuPage.getTotal());
        pageResult.setRecords(categoryMenuPage.getResult());
        pageResult.setSize((long) categoryMenuPage.getPageSize());
        pageResult.setCurrent((long) categoryMenuPage.getPageNum());
        pageResult.setOptimizeCountSql(true);
        pageResult.setSearchCount(true);
        return new Result("success",pageResult);
    }

    //增加菜单
    @PostMapping("/add")
    public Result add(@RequestBody Map<String,Object> categoryMenuVO){
        categoryMenuService.add(categoryMenuVO);
        return new Result("success","操作成功");
    }

    //编辑菜单
    @PostMapping("/edit")
    public Result edit(@RequestBody Map<String,Object> categoryMenuVO){
        categoryMenuService.edit(categoryMenuVO);
        return new Result("success","操作成功");
    }

    //删除菜单
    @PostMapping("/delete")
    public Result delete(@RequestBody Map<String,Object> categoryMenuVO){
        try {
            categoryMenuService.delete(categoryMenuVO);
            return new Result("success","操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error","该菜单下还有子菜单！");
        }
    }

    //获取所有菜单列表
    @GetMapping("/getAll")
    public Result getAll(String keyword){
        List<CategoryMenu> categoryMenuList=categoryMenuService.getAllByKeyword(keyword);
        return new Result("success",categoryMenuList);
    }

    //获取所有二级菜单-按钮列表
    @GetMapping("/getButtonAll")
    public Result getButtonAll(String keyword){
        List<CategoryMenu> categoryMenuList=categoryMenuService.getAll2MenuLevelByKeyword(keyword);
        return new Result("success",categoryMenuList);
    }

    //置顶菜单
    @PostMapping("/stick")
    public Result stick(@RequestBody Map<String,Object> categoryMenuVO){
        try {
            categoryMenuService.stick(categoryMenuVO);
            return new Result("success","操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("error",e.getMessage());
        }
    }
}
